# Configuration Reference #

The configuration used by the Service Gateway consists of 2 or more JSON (JavaScript Object Notation) files that define the *Roles* exposed by the Gateway as well as other shared services, such as *Authentication* and *Logging*.

## Role Index ##

The first mandatory JSON configuration file is the **Role Index** file. This file contains URL references to separate configuration files for each role as well as shared service configuration.

The format of the Role Index file is as follows:

	    {
	      Roles : {
	        "roleName" : URL to role configuration file,
	          ...
	        "_Default" : URL to default configuration file
	      }
	      Directory : Name of AAD tenant for AuthN,
	      ApplicationName : Name of AAD Application
	    }
 
where:

`roleName` is the name of each exposed role. The name will be used as the first segment in the requesting URL. eg. For a Gateway located at `http://myapp.com` with a role defined as `wiki`, the URL `http://myapp.com/wiki` will result in the request being routed to this role. Additional role entries may be added for other roles exposed by the Gateway.

`_Default` is a special role name that represents the base role. ie. When no URL path segment is specified in the request. This is an optional entry but if omitted any requests to the root of the Gateway application will result in a 404 (Resource not found) error being returned to the user.

`Directory` is the domain name of the *Azure Active Directory (AAD)* tenant that will be used for authenticating users to the web site. This value may be any of the registered domain names in the desired tenancy. This attribute is optional if AAD authentication is not required.

`ApplicationName` is the *App ID URI* representing the AAD application that will be used to authenticate users to the web site. The App ID URI uniquely identifies an application for authentication purposes and is associated with 1 or more Reply URL addresses - one of which must match the address of the deployed Gateway. This attribute is optional if AAD authentication is not required.

Full details for integrating authentication and authorization into the Gateway are provided in the [Authentication guide](Auth). For more information on using *Azure Active Directory* for Single Sign-On authentication please see [Adding Sign-On to Your Web Application Using Azure AD](http://msdn.microsoft.com/en-us/library/windowsazure/dn151790.aspx) on MSDN. 

## Role Configuration ##

As described above, each role exposed by a Gateway has its own configuration file. This enables role administrators to manage their role independently of other role administrators in the same application.

Aspects of role behavior that may be configured by this file include:

- Routing target
- Flights
- Path authorization

The format of the Role configuration file is:


	    {
		  "Target" : Target routing address,
	      "Treatment" : "Treatment name",
	      "Flights" : [
	        {
			  "Name"       : "Flight name",
			  "User"       : User(s),
			  "Tenant"     : Tenant(s),
			  "SourceIP"   : SourceIP(s),
			  "DomainName" : DomainNames(s),
			  "Target"     : Target routing address
	        },
			...
	      ],
		  "RequireAuthenticationBelow" : [
			"AuthPath1",
			"AuthPath2",
			...
		  ],
	      "Action" : [
			"Rewrite" (default) or
			"PermanentRedirect", 
			"FoundRedirect",
			"SeeOtherRedirect",
			"TemporaryRedirect"
	       ]
	    }
 
where:

**Routing target**

`Target` is the target routing address for the role or flight. This value may be a server name or IP address if protocol pass-through is required (https -> https, http -> http) or may be a fully qualified URL if protocol translation is required. ie. Regardless of what protocol the source request is sent over, all requests to the target will be sent using the protocol specified in the URL.

The Target for a role or flight may be specified in one of two forms i.e either a singular string or a collection of weighted routes for scenarios, such as A/B testing, where routing based on a weighted load balance algorithm is required.  Below is an example of each

Single target routing address:
	
        {
		   ...
		  "Target" : "channel9.msdn.com",
	       ...
	    }

Weighted load balance to target routing address':

	    {
		   ...
		   "Target":[   
					    {
			               "Weight":70,
			               "Redirect":"www.nickharris.net"
			            },
			            {
			               "Weight":30,
			               "Redirect":"chrisrisner.com"
			            },
						...
					]
	       ...
	    }

When a weighted load balance target is applied to either the Role or Flight requests will be distributed in proportion of the specified weighted value. eg. In the example above 70% of requests will be routed to the first target and 30% to the second. Note that this value is not necessarily a percentage, but is a relative proportion. Once a target is selected for a user agent session, it will be affinitized for the remainder of the session. This is the mechanism commonly used for performing A/B testing.

**Treatment**

`Treatment` defines which treatment rule is used to set which treatments are applied to the page content or the response header on the outbound path. This is most commonly used to fix paths that are different between the service gateway (public URL) and the downstream web assets (private URL).

This is an optional entry and defaults to "Rewrite" if left unset or if an invalid treatment is set.

Valid choices are:

*Individual treatments*

    ContentRewrite          - Rewrites the page content to fix all URL patterns to use the Gateway URL pattern
    LocationRedirect        - Rewrites the HTTP Location response header to fix all URL patterns to use the Gateway URL pattern
    ContentRewriteReturnUrl - Rewrites the ReturnUrl within URL patterns to fix all URL patterns to use the Gateway URL pattern
    BadCharsFix             - This is not useful by itself. URL Rewrite is unable to handle the "<![" string pattern in the content body and will fail to correctly rewrite the content after this string pattern. When this treatment is applied the ContentRewrite and ContentRewriteReturnUrl treatments will be able to work correctly. Since this treatment requires two extra passes of content rewriting, causing extra performance overhead, it's recommended to only apply this if needed.

*Treatment sets*

    Passthrough             - This will skip all treatments
    Rewrite                 - This will apply ContentRewrite, LocationRedirect, and ContentRewriteReturnUrl. This is the default treatment.
    RewriteAndFixup         - This will apply all treatments including the BadCharsFix treatment.

Examples of rewriting for Role address **public.com/blogconfig** include:

<table>
<tr>
  <th>Treatment</th><th>Private URL pattern in page content</th><th>URL pattern after treatment is applied</th><th>Notes</th>
</tr>
<tr>
  <td>Rewrite</td><td>http://private.com/page.aspx</td><td>http://public.com/blogconfig/page.aspx</td><td>Maintains protocol and domain. Updates path.</td>
</tr>
<tr>
   <td>Rewrite</td><td>https://private.com/page.aspx</td><td>https://public.com/blogconfig/page.aspx</td><td>Maintains protocol (https) and domain. Updates path.</td>
</tr>
<tr>
  <td>Rewrite</td><td>//private.com/page.aspx</td><td>//public.com/blogconfig/page.aspx</td><td>Maintains protocol relative pattern. Updates path.</td>
</tr>
<tr>
  <td>Rewrite</td><td>http://unrelated_url.com/page.aspx</td><td>http://unrelated_url.com/page.aspx</td><td>External unrelated URL. Left untouched.</td>
</tr>
<tr>
  <td>Rewrite</td><td>/page.aspx</td><td>/blogconfig/page.aspx</td><td>No need to prepend domain. Updates path.</td>
</tr>
<tr>
  <td>Rewrite</td><td>page.aspx</td><td>page.aspx</td><td>Not a relative page. Not updated.</td>
</tr>
<tr>
  <td>Rewrite</td><td>/p.aspx?ReturnURL=/page2.aspx</td><td>/blogconfig/p.aspx?ReturnURL=/blogconfig/page2.aspx</td><td>Updates path and ReturnURL path</td>
</tr>
<tr>
  <td>ContentRewrite</td><td>/p.aspx?ReturnURL=/page2.aspx</td><td>/blogconfig/p.aspx?ReturnURL=/page2.aspx</td><td>ContentRewrite treatment only updates the main URL pattern but doesn't update ReturnURL</td>
</tr>
</table>

   Note that `LocationRedirect` (included in `Rewrite` and `RewriteAndFixup`) will apply the same treatments as `ContentRewrite` mentioned above but to the HTTP `Response` header rather than the page content.

**Flights**

`Flights` is a collection of 1 or more flights that will be selected as the target route if the flight's criteria is met. This collection may be omitted if flighting is not required for this role.  

- `Name`: Is a unique name identifying each flight. Required.
- `User`: If authentication is enabled, the logged on user's UPN (User Principal Name, eg. fred@contoso.com) is compared to this value. The User property may be specified as a single string or a collection of strings i.e 
single user:
	
        {
		   ...
		  "User" : "jamesbak@gateway.onmicrosoft.com",
	       ...
	    }

	Or, collection of users:
	
        {
		   ...
		  "User" : ["jamesbak@gateway.onmicrosoft.com","dlan@gateway.onmicrosoft.com"]
	       ...
	    }


- `Tenant`: If authentication is enabled, the logged on user's tenant name (ie. the name following the @ character in the user's UPN. eg. fred@contoso.com will yield contoso.com) is compared to this value.
i.e 
single Tenant:
	
        {
		   ...
		  "Tenant" : "gateway.onmicrosoft.com",
	       ...
	    }

	Or, collection of tenants:
	
        {
		   ...
		  "Tenant" : ["gateway.onmicrosoft.com","nickha.com"]
	       ...
	    }
- `SourceIP`: The IPv4 address of the requesting computer is compared against this value. A full address may be specified or a complete subnet may be specified eg. 1.2.3.4 for exact match and 1.2.3. for match on ip range 1.2.3.0 - 1.2.3.255. Note that the IP address used may not necessarily be the requesting computer if the request has traveled through a outbound proxy server.
i.e 
singular:
	
        {
		   ...
		  "SourceIP" : "1.2.3.",
	       ...
	    }

	Or, collection of IP:
	
        {
		   ...
		  "SourceIP" : ["1.2.3.","10.10.10.10"]
	       ...
	    }
- `DomainName`: The domain name used to reach the gateway (the incoming request) is compared against this value. This is matched to full domain names. e.g. www.domain.com is an exact match (i.e. not 'ends with' or 'contains').
i.e 
singular:
	
        {
		   ...
		  "DomainName" : "www.domain.com",
	       ...
	    }

	Or, collection of Domain Names:
	
        {
		   ...
		  "DomainName" : ["www.domain.com","more.domain.com"]
	       ...
	    }
- `Target`: is the target routing address for the role or flight. Defined as per specification above. Required.

A given flight must specify a Name, Target and at least one Criteria SourceIP|User|Tenant. Any criteria that are not required should be omitted. 

*Flight evaluation:*

The order that the flight's are evaluated is in the order that they appear within config. Flight selection proceeds by evaluating the criteria of each flight and ends when the first flight's criteria is met.

If a combination of criteria is used the request must match at least one value in each of the specified criteria.  For example if a flight were specified with SourceIP of "1.2.3." and a Tenant of ["gateway.onmicrosoft.com","nickha.com"] then to route to the given target for this flight the originating source IP must be in the range of 1.2.3.0-1.2.3.255 AND the tenant of the authenticated user must be ("gateway.onmicrosoft.com" OR "nickha.com")

**Path authorization**

`RequireAuthenticationBelow` is an array of paths that will enforce valid authentication for matching requests. This attribute is only applicable if authentication is enabled. Any path on this role that is not included in this list will not require valid authentication. eg. a home or landing page.

**Action**

`Action` is an optional property to offer support for a redirect to another URL rather than reverse proxying the request. 

The options are:

- `Rewrite` (default) This is the normal Gateway behavior where the input URL is rewritten and the request is proxied to the new location
- `PermanentRedirect` - 301 HTTP Status code
- `FoundRedirect` - 302 HTTP Status code
- `SeeOtherRedirect` - 303 HTTP Status code
- `Temporary` - 307 HTTP Status code
